<template>
  <div class="gift-container">
    <el-card>
      <!-- 搜索 -->
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="listQuery.name"
            @clear="getGiftPackList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGiftPackList"
            >
            </el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >
            新增{{ title }}
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 列表 -->
      <el-table
        style="width: 100%"
        v-loading="listLoading"
        highlight-current-row
        border
        size="small"
        :data="datas"
      >
        <el-table-column label="#" align="center" type="index" width="50">
        </el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align ? column.align : 'center'"
          :width="column.width ? column.width : ''"
        >
          <template slot-scope="scope">
            <span
              v-if="column.key == 'is_show_name'"
              :style="{
                color: scope.row.is_show == 0 ? 'red' : '',
                fontWeight: 'bold',
              }"
            >
              {{ scope.row[column.key] }}
            </span>
            <span v-else>{{ scope.row[column.key] }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="handleEdit(scope)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 弹框 -->
    <el-dialog :title="getTitle" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="width: 95%"
      >
        <el-form-item label="礼包编号" prop="card_no">
          <el-input
            v-model="form.card_no"
            placeholder="礼包编号"
            maxlength="32"
            clearable
          />
        </el-form-item>
        <el-form-item label="礼包名称" prop="gift_name">
          <el-input v-model="form.gift_name" placeholder="礼包名称" clearable />
        </el-form-item>
        <el-form-item label="礼包明细" prop="goods">
          <el-transfer
            v-model="form.goods"
            :data="goods"
            filterable
            :titles="['待选商品', '已选商品']"
          ></el-transfer>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="form.comment" placeholder="备注" clearable />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getGiftPacks,
  addGiftPack,
  delGiftPack,
  updateGiftPack,
  delGiftPacks,
  getGoodsCodeList,
} from "@/api/shopping";

const defaultForm = {
  id: null,
  card_no: null,
  gift_name: null,
  goods: [],
  comment: null,
};

export default {
  name: "GiftPack",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        card_no: [{ required: true, message: "请输入卡号", trigger: "blur" }],
        gift_name: [
          { required: true, message: "请输入礼包名称", trigger: "blur" },
        ],
      },
      title: "礼包",
      dialogType: "new",
      dialogVisible: false,
      listLoading: true,
      datas: [],
      goods: [],
      total: 0,
      listQuery: {
        name: null,
      },
      tableColumns: [
        {
          key: "card_no",
          title: "礼包编号",
          align: "center",
          width: "150px",
        },
        {
          key: "gift_name",
          title: "礼包名称",
          align: "left",
          width: "240px",
        },
        {
          key: "goods_list",
          title: "礼包明细",
          align: "left",
        },
        {
          key: "comment",
          title: "备注",
        },
      ],
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `修改${this.title}`;
    },
  },
  created() {
    this.getGoodsList();
    this.getGiftPackList();
  },
  methods: {
    //获取商品列表
    getGoodsList() {
      getGoodsCodeList().then((res) => {
        console.log(res);
        this.goods = res.map((item) => {
          return {
            key: item.id,
            label: item.name,
          };
        });
      });
    },
    //获取列表
    getGiftPackList() {
      this.listLoading = true;
      getGiftPacks(this.listQuery)
        .then((res) => {
          this.total = res.length;
          this.datas = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.listLoading = false;
        });
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },

    //回显信息，弹框显示
    handleEdit(scope) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.form = scope.row;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    //更新信息
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        if (this.dialogType == "new") {
          res = await addGiftPack(this.form);
        } else {
          res = await updateGiftPack(this.form);
        }
        this.getGiftPackList();

        const { card_no, gift_name } = res;
        this.dialogVisible = false;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>礼包编号: ${card_no}</div>
              <div>礼包名称: ${gift_name}</div>
            `,
          type: "success",
        });
      });
    },
    //删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delGiftPack(row.id);
          this.datas.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
};
</script>
<style lang="scss" scoped>

</style>